package com.training.admin.web.controller.projectdata;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;
import com.training.admin.dto.ProjectDateRquest;
import com.training.admin.entity.category.TrainingCategory;
import com.training.admin.entity.department.Department;
import com.training.admin.entity.project.Project;
import com.training.admin.entity.project.ProjectPhase;
import com.training.admin.entity.search.ProjectDataSearch;
import com.training.admin.entity.security.Login;
import com.training.admin.entity.trainee.IdmUser;
import com.training.admin.entity.trainer.Trainer;
import com.training.admin.service.DataService;
import com.training.admin.service.DepartmentService;
import com.training.admin.service.IdmUserService;
import com.training.admin.service.ProjectDataService;
import com.training.admin.service.TrainingCategoryService;
import com.training.admin.web.resolver.Secure;

/**
 * 
 * @author Rockett
 * 
 */
@Controller
@RequestMapping("/project-data")
@MenuSetting("menu-training-project")
public class ProjectDataController {

	private static final Logger logger = LoggerFactory.getLogger(ProjectDataController.class);

	@Autowired
	private TrainingCategoryService trainingCategoryService;
	
	@Autowired
	private DepartmentService departmentService;
	
	@Autowired
	private ProjectDataService projectDataService;

	@Autowired
	@Qualifier("dataService")
	private DataService<Trainer> trainerService;
	

	@Autowired
	private IdmUserService idmUserService;

	/**
	 * 列表页
	 * 
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	@MenuSetting("submenu-project-data-management")
	public ModelAndView list(@Secure Login login, Page page, HttpServletRequest request) {

		ModelAndView modelAndView = new ModelAndView("project-data/project-data-list");
		
		int totals = projectDataService.count(login.getDepartmentId());
		
		if(totals > 0) {
			
			List<Project> projects = projectDataService.list(login.getDepartmentId(), page.with(totals));
			
			modelAndView.addObject("page", page);
			modelAndView.addObject("projects", projects);
			modelAndView.addObject("totals", totals);
			
			modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "filter", "page"));
		}
		

		return modelAndView;
	}
	
	/**
	 * 
	 * @return
	 */
	@RequestMapping(value = "/search", method = RequestMethod.GET)
	@MenuSetting("submenu-project-data-management")
	public ModelAndView search(@Secure Login login) {

		ModelAndView modelAndView = new ModelAndView("project-data/project-data-search");
		
		
		List<Department> departmentList = projectDataService.list(login.getDepartmentId());
	
		modelAndView.addObject("departmentList", departmentList);

		return modelAndView;
	}

	/**
	 * onSearch
	 * 
	 * @param projectSearch
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/search", method = RequestMethod.GET, params = "filter")
	@MenuSetting("submenu-project-data-management")
	public ModelAndView onSearch(@Secure Login login, ProjectDataSearch projectDataSearch, HttpServletRequest request, Page page) {

		ModelAndView modelAndView = new ModelAndView("project-data/project-data-list");

		int totals = projectDataService.count(login.getDepartmentId(), projectDataSearch);
		
		if (totals > 0) {

			List<Project> projectList = projectDataService.onSearch(login.getDepartmentId(), projectDataSearch, page.with(totals));

			modelAndView.addObject("projects", projectList);
			modelAndView.addObject("page", page);
			
			modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));

		}

		return modelAndView;

	}

	

	

	/**
	 * 新增项目
	 * 
	 * @return
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	@MenuSetting("submenu-project-data-management")
	public ModelAndView create() {
		ModelAndView modelAndView = new ModelAndView("project-data/project-data-create");
		return modelAndView;
	}

	/**
	   *     新增提交
	 * @param project
	 * @return
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-project-data-management")
	public @ResponseBody HttpResult onCreate(Project project) {
		HttpResult httpResult = new HttpResult();
	
		try {
	  
			project = projectDataService.createProject(project);
	       
			httpResult.success().message("新增项目成功").data("url", "/project-data/" + project.getId() + "/detail");
	
		} catch (BusinessException e) {
	    
		    httpResult.fail(e.getCode()).message(e.getMessage());
		    logger.error("onCreate occurs error: ", e);
	
		} catch (Exception e) {
		    logger.error("onCreate occurs error: ", e);
		    httpResult.fail("500").message("新增项目失败");
		}
		
		return httpResult;
	}

	/**
	 * 修改项目
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
	@MenuSetting("submenu-project-data-management")
	public ModelAndView edit(@PathVariable("id") Long id) {
		ModelAndView modelAndView = new ModelAndView("project-data/project-data-edit");
		
		Project project = projectDataService.load(Project.class, id);
		modelAndView.addObject("project", project);
		
		modelAndView.addObject("projectLead", project.getProjectLead());
	
		IdmUser idmUser = idmUserService.getIdmUser( project.getProjectLead());
		modelAndView.addObject("idmUser", idmUser);
		
		return modelAndView;
	}

	/**
	 * 修改项目提交
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-project-data-management")
	public @ResponseBody HttpResult onEdit(@Preloading("projectId") Project project,@RequestParam Long firstCategoryId,
	        @RequestParam Long secondCategoryId, @RequestParam(name="departmentId", required = false) Long departmentId) {

		HttpResult httpResult = new HttpResult();
		
		try {
		    
		    TrainingCategory firstCategory = trainingCategoryService.load(TrainingCategory.class, firstCategoryId);
            TrainingCategory secondCategory = trainingCategoryService.load(TrainingCategory.class, secondCategoryId);
		    if (departmentId != null) {
               
		    	Department department = departmentService.load(Department.class, departmentId);
                projectDataService.updateProject(project, firstCategory, secondCategory, department);
                httpResult.success().message("修改项目成功");
			} /*
				 * else { projectDataService.update(project, firstCategory, secondCategory);
				 * httpResult.success().message("修改项目成功"); }
				 */

        } catch (Exception e) {
            httpResult.fail("500").message("修改项目失败");
            logger.error("#onEdit() - edit fail, exception is [{}]", e);
        }

		return httpResult;

	}

	/**
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/phases", method = RequestMethod.GET)
	@MenuSetting("submenu-project-data-management")
	public ModelAndView editPhase(@PathVariable("id") Long id) {
	
		ModelAndView modelAndView = new ModelAndView("project-data/project-data-phase");
			
		List<ProjectPhase> projectPhase = projectDataService.listProjectPhaseById(id);
			modelAndView.addObject("projectPhases", projectPhase);
		
		return modelAndView;
	}

	/**
	 * 
	 * @param id
	 * @param projectDateRquest
	 * @return
	 */
	@RequestMapping(value = "/{id}/phases", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public HttpResult onEditPhase(@PathVariable("id") Long id, ProjectDateRquest projectDateRquest) {
		
		HttpResult httpResult = new HttpResult();
		
		try {
			
			projectDataService.editPhasesDate(id, projectDateRquest);
			httpResult.success().message("设置成功");
			
		} catch (Exception e) {
	
			logger.error("#onEditPhase onccurs error", e);
			httpResult.fail("500").message("设置失败");
		}
		
		return httpResult;
		
	}

	/**
	 * 删除项目
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
	@MenuSetting("submenu-project-data-management")
	public ModelAndView disable(@PathVariable("id") Long id) {
		ModelAndView modelAndView = new ModelAndView("project-data/project-data-delete");
		Project project = projectDataService.load(Project.class, id);
		modelAndView.addObject("project", project);
		return modelAndView;
	}

	/**
	 * 删除项目提交
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-project-data-management")
	public @ResponseBody HttpResult onDisable(@PathVariable("id") Long id) {
		HttpResult httpResult = new HttpResult();
		try {
			
			projectDataService.delete(id);
			httpResult.success().message("删除项目信息成功");
		
		} catch (Exception e) {
			
			httpResult.fail("500").message("删除项目信息失败! " + e.getMessage());
			logger.error("#onDisable() - delete project fail, exception is [{}]", e);
		
		}

		return httpResult;

	}
	
	/**
	 * 复制项目
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/copy", method = RequestMethod.GET)
    @MenuSetting("submenu-project-data-management")
    public ModelAndView copy(@PathVariable("id") Long id) {
        ModelAndView modelAndView = new ModelAndView("project-data/project-data-copy");
        Project project = projectDataService.load(Project.class, id);
        modelAndView.addObject("project", project);
        return modelAndView;
    }
	
	/**
     * 复制项目提交
     * 
     * @return
     */
    @RequestMapping(value = "/{id}/copy", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @MenuSetting("submenu-project-data-management")
    public @ResponseBody HttpResult onCopy(@PathVariable("id") Long id) {
        HttpResult httpResult = new HttpResult();
        try {
            
            projectDataService.copy(id);
            httpResult.success().message("复制项目信息成功");
        
        } catch (Exception e) {
            
            httpResult.fail("500").message("复制项目信息失败! " + e.getMessage());
            logger.error("#onDisable() - delete project fail, exception is [{}]", e);
        
        }

        return httpResult;

    }
	
}
